import { FC, useEffect, useState } from "react";
import { css } from "@emotion/css";
import {
  DatePicker,
  Form,
  Message,
  Space,
  Button,
  Tooltip,
} from "@arco-design/web-react";
import { useAPI } from "../../hooks/useAPI.ts";
import dayjs from "dayjs";
import Box from "@mui/material/Box";
import { zhCN } from "@mui/x-data-grid";
import {
  findRisk,
  StripedDataGrid,
  timestampToLocalTime,
} from "./ActivityListAndRecord.tsx";
import { ViewVideoRecordModal } from "../ViewVideoRecordModal";
import { Icon } from "@iconify/react";

export const reportTime = (report: any) => {
  if (report === null || report === "null") return "/";
  return JSON.parse(report)["time"];
};

export const reportResult = (report: any) => {
  if (report === null || report === "null") return "未处理";
  return JSON.parse(report).method === 0 ? "系统误报" : "人工处理";
};

export const reportName = (report: any) => {
  if (report === null || report === "null") return "/";
  if (isJsonString(report)) {
    return JSON.parse(report).report.nickName;
  } else {
    return report
  }
};


export function isJsonString(str: string) {
  try {
    const result = JSON.parse(str);
    return typeof result === 'object' && result !== null;
  } catch (e) {
    return false;
  }
}

export function loadServerRows(
  paginationModel: any,
  dateRange: any,
  userId: number | string,
  api: any,
  riskLevel: any,
  search?: any,
): Promise<any> {
  return api.getRiskProcessingLogs({
    userId,
    startDate: dateRange[0],
    endDate: dateRange[1],
    start: paginationModel.page,
    length: paginationModel.pageSize,
    riskLevel: riskLevel,
    search: search,
  });
}

export const RiskHandleRecord: FC<{ userId: number | string }> = ({
  userId,
}) => {
  const [dateRange, setDateRange] = useState([
    dayjs().subtract(30, "day").format("YYYY-MM-DD"), // Yesterday
    dayjs().format("YYYY-MM-DD"), // Today
  ]);
  const [loading, setLoading] = useState(false); // Loading state
  const [data, setData] = useState({
    data: [],
    recordsTotal: 0,
  }); // Loading state
  const [paginationModel, setPaginationModel] = useState({
    page: 0,
    pageSize: 10,
  });
  const [suid, setSuid] = useState("");
  const [report, setReport] = useState("null");
  const [id, setId] = useState<number>(-1);
  const [isOpenViewVideoRecordModal, setIsViewVideoRecordModal] =
    useState(false);
  const [time, setTime] = useState("");
  const [refresh, setRefresh] = useState(false);
  const [search] = useState("");
  const [action, setAction] = useState(null);
  const api = useAPI();

  const deleteRecord = (id: number) => {
    api
      .deleteRiskProcessingLog({
        id,
        userId,
        suid,
        data: {
          pics: "", files: "",
          method: 0,
          report: {
            userId: window.localStorage.getItem("loggedUserId"),
            nickName: window.localStorage.getItem("loggedNickName"),
          },
          time: dayjs().format("YYYY-MM-DD HH:MM:s"),
        },
      })
      .then((r) => {
        if (r.data.code == "3001") {
          Message.info("操作成功");
          setRefresh(!refresh);
        }
      });
  };

  useEffect(() => {
    setLoading(true);
    loadServerRows(paginationModel, dateRange, userId, api, 0, search).then(
      (response) => {
        response.data.data = response.data?.data.map(
          (row: any, index: number) => ({
            index: index + 1 + paginationModel.page * paginationModel.pageSize, // Add index starting from 1
            ...row,
          }),
        );
        setData(response.data);
        setLoading(false);
      },
    );
  }, [paginationModel, refresh, dateRange, search]);

  useEffect(() => {
    const timer = setInterval(async () => {
      // setNotification(window.localStorage.getItem("refresh"));
    }, 100);

    return () => {
      clearInterval(timer);
    };
  }, []);

  return (
    <div>
      <ViewVideoRecordModal
        videoList={suid}
        id={id}
        userId={userId}
        report={report}
        visible={isOpenViewVideoRecordModal}
        eventTime={time}
        action={action}
        onClose={() => setIsViewVideoRecordModal(false)}
        refresh={() => setRefresh(!refresh)}
        deleteRecord={deleteRecord}
      />
      <h3
        className={css`
          border-left: 3px solid rgb(var(--primary-6));
          padding-left: 12px;
          border-radius: 2px;
          margin-bottom: 30px;
        `}
      >
        风险处理日志内容
      </h3>
      <Form layout="inline">
        <Form.Item label="按时间查询：">
          <DatePicker.RangePicker
            onChange={(e) => {
              setDateRange(e);
            }}
            onClear={() => {
              setDateRange(["", ""]);
            }}
            defaultValue={dateRange}
            disabledDate={(current) => current.isAfter(dayjs())}
            shortcuts={[
              {
                text: "上一周",
                value: () => [dayjs(), dayjs().subtract(1, "week")],
              },
              {
                text: "上一个月",
                value: () => [dayjs(), dayjs().subtract(1, "month")],
              },
              {
                text: "上一年",
                value: () => [dayjs(), dayjs().subtract(1, "year")],
              },
            ]}
            style={{ width: "250px" }}
          />
        </Form.Item>
      </Form>
      <Box sx={{ height: 500, width: "100%", marginTop: "16px" }}>
        {data.data ? (
          <StripedDataGrid
            density="compact"
            rows={data.data}
            rowCount={data.recordsTotal}
            loading={loading}
            getRowClassName={(params) =>
              params.indexRelativeToCurrentPage % 2 === 0 ? "even" : "odd"
            }
            columns={[
              {
                field: "index",
                headerName: "序号",
                minWidth: 5,
                align: "center", // Center the cell content
                headerAlign: "center", // Center the header content
              },
              {
                field: "startTime",
                headerName: "记录时间",
                valueGetter: (value: any) =>
                  timestampToLocalTime(value.row.startTime * 1000.0),
                minWidth: 180,
                align: "center", // Center the cell content
                headerAlign: "center", // Center the header content
              },
              {
                field: "actCn",
                headerName: "活动名称",
                align: "center", // Center the cell content
                headerAlign: "center", // Center the header content
              },
              {
                field: "reportT",
                headerName: "处理时间",
                valueGetter: (value: any) => reportTime(value.row.report),
                minWidth: 180,
                align: "center", // Center the cell content
                headerAlign: "center", // Center the header content
              },
              {
                field: "reportR",
                headerName: "处理结果",
                valueGetter: (value: any) => reportResult(value.row.report),
                align: "center", // Center the cell content
                headerAlign: "center", // Center the header content
              },
              {
                field: "reportU",
                headerName: "处理人",
                valueGetter: (value: any) => reportName(value.row.report),
                align: "center", // Center the cell content
                headerAlign: "center", // Center the header content
              },
              {
                field: "riskLevel",
                headerName: "风险等级",
                renderCell: (value: any) => findRisk(value.row.riskLevel),
                align: "center", // Center the cell content
                headerAlign: "center", // Center the header content
              },
              {
                field: "cmd",
                headerName: "查看回放",
                align: "center", // Center the cell content
                headerAlign: "center", // Center the header content
                renderCell: (value: any) => {
                  const suid = JSON.parse(value.row.suid);
                  return suid?.length > 0 ? (
                    <Space>
                      <Tooltip content="查看回放">
                        <Button
                          size="small"
                          shape="round"
                          type="outline"
                          icon={<Icon icon="tabler:repeat" />}
                          onClick={(e) => {
                            e.preventDefault();
                            e.stopPropagation();
                            setIsViewVideoRecordModal(true);
                            setSuid(suid.length > 0 ? suid[0] : "");
                            setReport(value.row.report);
                            setId(value.row.id);
                            setAction(value.row.actCn);
                            setTime(
                              timestampToLocalTime(
                                value.row.startTime * 1000.0,
                              ),
                            );
                          }}
                        />
                      </Tooltip>
                    </Space>
                  ) : (
                    <div>无</div>
                  );
                },
                minWidth: 200,
              },
            ]}
            paginationMode="server"
            paginationModel={paginationModel}
            onPaginationModelChange={setPaginationModel}
            pageSizeOptions={[10]}
            disableRowSelectionOnClick
            localeText={zhCN.components.MuiDataGrid.defaultProps.localeText}
          />
        ) : null}
      </Box>
    </div>
  );
};
